package com.wnhoo.smartfishtank.fishtank;

import android.app.AlertDialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TimePicker;

import com.wnhoo.smartfishtank.R;
import com.wnhoo.smartfishtank.api.LM_TimingAPI;
import com.wnhoo.smartfishtank.api.data.DataTiming;
import com.wnhoo.smartfishtank.api.data.LM_DataSend;
import com.wnhoo.smartfishtank.app.LMAPP;
import com.wnhoo.smartfishtank.base.BaseActivity;
import com.wnhoo.smartfishtank.util.MyLog;
import com.wnhoo.smartfishtank.util.ShowToastUtil;

import java.util.Calendar;
import java.util.List;

public class Light_Timing_ItemActivity extends BaseActivity implements BaseActivity.InitHeaderListener {

    private RelativeLayout timer_open_layout, timer_close_layout, timer_color_layout, light_timing_rel_delete;
    private Calendar calendar;
    private TextView timing_text_open, timing_text_close;
    private TextView timing_img_color;
    private int item_Position;
    private DataTiming dataTiming;
    private List<DataTiming> list_timing;
    private String timingColor;//当前选中的是哪个颜色
    private int getItem_Position;//当前选中的颜色在列表中的位置
    private boolean isDelete = false;//是否现在进行的删除操作

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_light__timing__item);
        setOnInitListener(this);
        initView();
        initData();
    }


    @Override
    public void initView() {
        super.initView();
        calendar = Calendar.getInstance();

        timer_open_layout = (RelativeLayout) findViewById(R.id.timer_open_layout);
        timer_close_layout = (RelativeLayout) findViewById(R.id.timer_close_layout);
        timer_color_layout = (RelativeLayout) findViewById(R.id.timer_color_layout);
        light_timing_rel_delete = (RelativeLayout) findViewById(R.id.light_timing_rel_delete);
        timing_text_open = (TextView) findViewById(R.id.timing_text_open);
        timing_text_close = (TextView) findViewById(R.id.timing_text_close);
        timing_img_color = (TextView) findViewById(R.id.timing_img_color);

        timer_open_layout.setOnClickListener(this);
        timer_close_layout.setOnClickListener(this);
        timer_color_layout.setOnClickListener(this);
        light_timing_rel_delete.setOnClickListener(this);
    }

    private void initData() {
        item_Position = getIntent().getIntExtra("position", -1);
        list_timing = Light_Timing_ListActivity.instance.getList_timing();
        dataTiming = list_timing.get(item_Position);
        Log.i("light_Timing", "dataTiming.isSend_timing()" + dataTiming.isSend_timing());
        if (dataTiming.isSend_timing()) {
            timing_text_open.setText(dataTiming.getTime_open());
            timing_text_close.setText(dataTiming.getTime_colse());
//            showColor(dataTiming.getColor());
        } else {
//            timing_img_color.setText("深绿");
//            timingColor = "33cc33";
        }
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.timer_open_layout:
                showTimePickerDialog(
                        new TimePickerDialog.OnTimeSetListener() {
                            @Override
                            public void onTimeSet(TimePicker timePicker, int hour, int minute) {

                                StringBuffer sb = new StringBuffer();
                                if (hour < 10) sb.append("0");
                                sb.append(hour).append(":");
                                if (minute < 10) sb.append("0");
                                sb.append(minute);
                                timing_text_open.setText(sb.toString());
                            }
                        });
                break;
            case R.id.timer_close_layout:
                showTimePickerDialog(
                        new TimePickerDialog.OnTimeSetListener() {
                            @Override
                            public void onTimeSet(TimePicker timePicker, int hour, int minute) {
                                StringBuffer sb = new StringBuffer();
                                if (hour < 10) sb.append("0");
                                sb.append(hour).append(":");
                                if (minute < 10) sb.append("0");
                                sb.append(minute);
                                timing_text_close.setText(sb.toString());
                            }
                        });
                break;
            case R.id.timer_color_layout:
//                showDeleteView();
                showPickerView();
                break;
            case R.id.light_timing_rel_delete:
                showDeleteView();
                break;
        }
    }

    static final String[] stringColor = {"深绿", "绿色", "淡黄", "深蓝", "天蓝", "淡绿"};

    /**
     * 显示滑动选择菜单按钮
     */
    private void showPickerView() {


        AlertDialog.Builder builder = new AlertDialog.Builder(
                this);


        builder.setSingleChoiceItems(stringColor, getItem_Position,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,
                                        int whichButton) {
                        getSelectColor(stringColor[whichButton]);

                    }
                });
        builder.setPositiveButton(getStringXml(R.string.ok),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,
                                        int whichButton) {
                        dialog.dismiss();
                    }
                });
        builder.create().show();
    }

    /**
     * 根据用户的点击获取用户选择的颜色
     *
     * @param s
     */
    private void getSelectColor(String s) {
        switch (s) {
            case "深绿":
                timing_img_color.setBackgroundColor(getResources().getColor(R.color.timing_color1));
                timingColor = "33cc33";
                getItem_Position = 0;
                break;
            case "绿色":
                timing_img_color.setBackgroundColor(getResources().getColor(R.color.timing_color2));
                timingColor = "66cc66";
                getItem_Position = 1;
                break;
            case "淡黄":
                timing_img_color.setBackgroundColor(getResources().getColor(R.color.timing_color3));
                timingColor = "cccc66";
                getItem_Position = 2;
                break;
            case "深蓝":
                timing_img_color.setBackgroundColor(getResources().getColor(R.color.timing_color4));
                timingColor = "4c4ccc";
                getItem_Position = 3;
                break;
            case "天蓝":
                timing_img_color.setBackgroundColor(getResources().getColor(R.color.timing_color5));
                timingColor = "4c4ccc";
                getItem_Position = 4;
                break;
            case "淡绿":
                timing_img_color.setBackgroundColor(getResources().getColor(R.color.timing_color6));
                timingColor = "7fcc7f";
                getItem_Position = 5;
                break;
        }
    }

    /**
     * 显示删除
     */
    private void showDeleteView() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(getStringXml(R.string.prompt)).setMessage(getStringXml(R.string.del_timing))
                .setNegativeButton(getStringXml(R.string.cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
        builder.setPositiveButton(getStringXml(R.string.ok), new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                delDevice();
                isDelete = true;
            }
        });
        builder.show();
    }

    private void delDevice() {
        list_timing.remove(dataTiming);
        updateTiming(true);
    }

    /**
     * 根据十六进制的颜色显示对应的颜色
     *
     * @param color
     */
    public void showColor(String color) {
        switch (color) {

            case "33cc33":
                timing_img_color.setBackgroundColor(getResources().getColor(R.color.timing_color1));
                timingColor = "33cc33";
                getItem_Position = 0;
                break;
            case "66cc66":
                timing_img_color.setBackgroundColor(getResources().getColor(R.color.timing_color2));
                timingColor = "66cc66";
                getItem_Position = 1;
                break;
            case "cccc66":
                timing_img_color.setBackgroundColor(getResources().getColor(R.color.timing_color3));
                timingColor = "cccc66";
                getItem_Position = 2;
                break;
            case "4c4ccc":
                timing_img_color.setBackgroundColor(getResources().getColor(R.color.timing_color4));
                timingColor = "4c4ccc";
                getItem_Position = 3;
                break;
            case "4ccccc":
                timing_img_color.setBackgroundColor(getResources().getColor(R.color.timing_color5));
                timingColor = "4c4ccc";
                getItem_Position = 4;
                break;
            case "7fcc7f":
                timing_img_color.setBackgroundColor(getResources().getColor(R.color.timing_color6));
                timingColor = "7fcc7f";
                getItem_Position = 5;
                break;
        }
    }

    public void showTimePickerDialog(TimePickerDialog.OnTimeSetListener l) {

        calendar.setTimeInMillis(System.currentTimeMillis());
        int mHour = calendar.get(Calendar.HOUR_OF_DAY);
        int mMinute = calendar.get(Calendar.MINUTE);
        TimePickerDialog dialog = new TimePickerDialog(Light_Timing_ItemActivity.this,
                l, mHour, mMinute, true);
        dialog.show();
    }

    @Override
    public void OnSetTitle(TextView t) {
        t.setTextColor(this.getResources().getColor(R.color.ther_text_color));
        t.setText(getStringXml(R.string.timing_setting));
    }

    @Override
    public void OnSetLeftView(Button btn) {
        btn.setVisibility(View.VISIBLE);
    }

    @Override
    public void OnSetRightView(Button btn) {
        btn.setVisibility(View.VISIBLE);
    }

    @Override
    public void OnSetLeftOnclick(View view) {

    }

    @Override
    public void OnSetRightOnclick(View view) {
        if (timing_text_open.getText().equals("") || timing_text_open.getText() == null) {
            ShowToastUtil.show(getApplication(), "请输入启动时间");
            return;
        } else if (timing_text_close.getText().equals("") || timing_text_close.getText() == null) {
            ShowToastUtil.show(getApplication(), "请输入结束时间");
            return;
        }
        //点击了保存按钮
        dataTiming.setTime_open(timing_text_open.getText().toString());
        dataTiming.setTime_colse(timing_text_close.getText().toString());
//        dataTiming.setColor(timingColor);
        dataTiming.setSend_timing(true);
        dataTiming.setPerion_value("ff");
        updateTiming(true);

        Log.i(TAG, "list_timing" + list_timing);
    }

    @Override
    public void onSetbackground(View view) {
        view.setBackgroundResource(R.drawable.solid_shadow);
    }

    /**
     * listview更新timing
     *
     * @param
     */
    public void updateTiming(boolean isSendToClound) {
        MyLog.d(TAG, "updateTiming*********************************");
//        if(list!=null){
//            list_timing.clear();
//            for(DataTiming data:list){
//                list_timing.add(data);
//            }
//        }
//        adapterLightTiming.notifyDataSetChanged();
        if (isSendToClound) {
            MyLog.d(TAG, "updateTiming 发到云端");
            AsyncTaskSend asyncTaskSend = new AsyncTaskSend();
            asyncTaskSend.execute("");
//            Light_Timing_ListActivity.instance.sendToClound();
        } else {
            MyLog.d(TAG, "updateTiming 不发到云端");
        }
    }

    /**
     * 向服务器发送定时数据
     */
    class AsyncTaskSend extends AsyncTask<String, Integer, LM_DataSend> {//继承AsyncTask

        @Override
        protected LM_DataSend doInBackground(String... params) {//处理后台执行的任务，在后台线程执行
            LM_DataSend data = null;
            try {
                data = LM_TimingAPI.sendTimingList(list_timing, LMAPP.dataPlug.getId(), LMAPP.token_default,1);

            } catch (Exception e) {
                MyLog.exception(e);
            }
            return data;
        }

        protected void onProgressUpdate(Integer... progress) {//在调用publishProgress之后被调用，在ui线程执行
        }

        protected void onPostExecute(LM_DataSend data) {//后台任务执行完之后被调用，在ui线程执行
            Log.i(TAG, "设置定时后的返回" + data.toString());
            if (!data.isResult()) {
                ShowToastUtil.showShort(getApplication(), "操作失败");
                return;
            }
            if (isDelete) {
                ShowToastUtil.showShort(getApplication(), "删除成功");
//                ColorActivity.instance.saveToSPF();
//                startActivity(new Intent(Light_Timing_ItemActivity.this, Light_Timing_ListActivity.class));
                finish();
            } else {
                ShowToastUtil.showShort(getApplication(), "定时成功");
//                ColorActivity.instance.saveToSPF();
//                startActivity(new Intent(Light_Timing_ItemActivity.this, Light_Timing_ListActivity.class));
                finish();
            }
        }

        protected void onPreExecute() {//在 doInBackground(Params...)之前被调用，在ui线程执行
        }

        protected void onCancelled() {//在ui线程执行
        }
    }
}
